# -*- coding: utf-8 -*-

'''eof
name:申请企业2年内未结清欠息次数校验
code:Ent_UnpaidDebtInterest_2YrCheck
tableName:
columnName:
groups:准入>企业征信校验
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:申请企业2年内未结清欠息次数校验
eof'''

'''
ECRUnpaidDebtInterest（未结清欠息）
BalanceChangedate	余额改变日期	String
余额改变日期在2年内 则计数

Owekindcode	欠息类型
PaidType	结清状态
Owebalancetormb	欠息余额（元）
BalanceChangedate	余额改变日期
结合其他字段去重
'''

import sys
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
import json

reload(sys)
sys.setdefaultencoding('utf-8')

last_year_list = [(datetime.datetime.now() - pd.tseries.offsets.DateOffset(years=i)).strftime('%Y-%m-%d')\
                    for i in [2, 0]]
#如果这个字段存在 但是里面的list长度为0 不包含任何dict 应该返回缺失值 不应该为0
def FormatData(tableName):
    try:
        ecr = json.loads(EC[0]["ecr"])[tableName]
        return ecr if isinstance(ecr, list) and len(ecr) > 0 else [{}]
    except:
        return [{}]

def Ent_UnpaidDebtInterest_2YrCheck():
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    verify = set()
    try:
        ECRUnpaidDebtInterest = FormatData('ECRUnpaidDebtInterest')
        if ECRUnpaidDebtInterest == [{}]:
            return u'缺失值'
        else:
            if  len(ECRUnpaidDebtInterest) >= 1:
                for i in ECRUnpaidDebtInterest:
                    if i.has_key('BalanceChangedate') \
                        and i['BalanceChangedate'] not in null_type_list \
                        and Formate(i['BalanceChangedate']) is not None:
                        if Formate(i['BalanceChangedate']) > last_year_list[0] \
                        and Formate(i['BalanceChangedate']) <= last_year_list[1]:
                            #去重验证
                            if (isExist(i['Owekindcode']) + isExist(i['PaidType']) + isExist(i['Owebalancetormb']) +\
                                        isExist(i['BalanceChangedate'])) not in verify:
                                verify.add((isExist(i['Owekindcode']) + isExist(i['PaidType']) + isExist(i['Owebalancetormb']) +\
                                        isExist(i['BalanceChangedate'])))
                            else:
                                pass
                        else:
                            verify.add(0)
                    else:
                        verify.add(None)
                if None in verify and len(verify) == 1:
                    return u'缺失值'
                else:
                    verify_notnone = [i for i in verify if i!= None and i!=0]
                    return len(verify_notnone)
            else:
                return u'缺失值'
    except:
        return u'缺失值'

#统一时间为 '2018-05-30'
def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y-%m-%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y-%m-%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y-%m-%d')
                except:
                    date = None
    return date
    # try:
    #     if tmp.isdigit() and len(tmp)>= 8:
    #        date = datetime.datetime.strptime(tmp[0:8],'%Y%m%d').strftime('%Y-%m-%d')
    #        return date
    #     elif tmp.isdigit() and len(tmp)>0 and len(tmp)<8:
    #         date = datetime.datetime.strptime(tmp,'%Y%m%d').strftime('%Y-%m-%d')
    #         return date
    #     else:
    #         return None
    # except:
    #     return None

def isExist(d):
    null_type_list = ['', None, 'null', 'Null', 'NULL', '/', ' ']
    if d not in null_type_list:
        return d
    else:
        return ''

result = Ent_UnpaidDebtInterest_2YrCheck()